package com.mlink.ai.chat

import android.app.Activity
import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.*
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adsdk.android.ads.AdEventCallback
import com.adsdk.android.ads.OxAdSdkManager
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import com.google.firebase.messaging.RemoteMessage
import com.icekrvams.air.InitializerProvider
import com.icekrvams.air.firebase.fcm.CloudMessaging
import com.icekrvams.air.firebase.fcm.FcmListener
import com.icekrvams.air.installreferrer.InstallReferrerCollector
import com.icekrvams.air.installreferrer.InstallReferrerTool
import com.icekrvams.billing.Billing
import com.icekrvams.billing.data.Products
import com.icekrvams.billing.listeners.BillingListener
import com.mike.moshi.AppManager
import com.mlink.ai.chat.assistant.robot.BuildConfig
import com.mlink.ai.chat.constants.SIGNATURE
import com.mlink.ai.chat.constants.SUB_ID_AICHAT_ONE_WEEK
import com.mlink.ai.chat.constants.SUB_ID_AICHAT_ONE_YEAR
import com.mlink.ai.chat.receiver.PromptLocalNotificationAlarmReceiver
import com.mlink.ai.chat.ui.viewmodel.AppViewModel
import com.mlink.ai.chat.utils.*
import java.util.*


class AiChatApplication : Application(), LifecycleObserver {
    companion object {
        lateinit var app: AiChatApplication
    }

    private var isAppForeground = false

    val appViewModel: AppViewModel by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(this).create(AppViewModel::class.java)
    }

    override fun onCreate() {
        super.onCreate()
        val currentProcessName = ProcessUtil.getCurrentProcessName(this)
        if (packageName.equals(currentProcessName)) {

            app = this

            InitializerProvider.init(this)

            initAdjustSDK()
            registerActivityLifecycleCallbacks(AppLifecycleCallbacks())

            ProcessLifecycleOwner.get().lifecycle.addObserver(this)

            initAdSdk()

            RemoteConfigWorker.start(this)

            InstallReferrerTool.fetchReferrer(this, object : InstallReferrerCollector {
                override fun onGetSignature(): String = SIGNATURE
            })

            initBilling()

            addFcmListener()

            schedulePromptLocalNotificationAlarm()

            PermanentUtil.init(this)
        }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)

        AppManager.init(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        isAppForeground = false
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        isAppForeground = true
    }

    fun isAppForeground(): Boolean {
        return isAppForeground
    }

    private fun initBilling() {
        val products = Products.Builder()
            .availableSubProducts(SUB_ID_AICHAT_ONE_WEEK, SUB_ID_AICHAT_ONE_YEAR) // 当前可用的订阅商品。
//            .deprecatedSubProducts("sub_deprecated_a") // 已下架的订阅商品。
//            .availableOneTimeIapProducts("one-time_iap_available_a") // 当前可用的一次性内购商品。
//            .deprecatedOneTimeIapProducts("one-time_iap_deprecated_a") // 已下架的一次性内购商品。
//            .consumableIapProducts("consumable_iap_a") // 可用的消耗性商品。
            .build()
        Billing.init(
            /* application */this,
            products,
            billingListener = object : BillingListener {

                override fun onPurchasesUpdated(
                    billingResult: BillingResult,
                    purchases: List<Purchase>?
                ) {
                    // PlayStore 购买页面回到应用时被调用。
                }

                override fun onQueryProductDetailsResponse(
                    billingResult: BillingResult,
                    productDetails: List<ProductDetails>?
                ) {
                    // 查询商品信息结果回调。
                }

                override fun onQueryPurchasesResponse(
                    billingResult: BillingResult,
                    purchasesList: List<Purchase>
                ) {
                    // 查询已拥有商品信息结果回调。
                }

                override fun onSubAcknowledged(purchase: Purchase) {
                    // 订阅商品被确认完成。
                }

                override fun onSubAcknowledgeFailed(
                    purchase: Purchase,
                    billingResult: BillingResult
                ) {
                    // 订阅商品确认失败。
                }

                override fun onOneTimeIapAcknowledged(purchase: Purchase) {
                    // 一次性内购商品确认完成。
                }

                override fun onOneTimeIapAcknowledgeFailed(
                    purchase: Purchase,
                    billingResult: BillingResult
                ) {
                    // 一次性内购商品确认失败。
                }

                override fun onConsumableIapConsumed(purchase: Purchase) {
                    super.onConsumableIapConsumed(purchase)
                    // 可消耗型商品消耗完成。
                }

                override fun onConsumableIapConsumeFailed(
                    purchase: Purchase,
                    billingResult: BillingResult
                ) {
                    // 可消耗型商品消耗失败。
                }
            }
        )
        // 默认关闭日志，可以将 logEnabled 设置为 ture，以开启日志，Tag 为 “BillingSdk”。
        Billing.logEnabled = BuildConfig.IS_DEV
    }

    private fun initAdSdk() {
        // 如果想更换默认⼴告平台（默认为MAX），需要在初始化之前调⽤。
        // OxAdSdkManager.getInstance().setDefaultMediationPlatform(Platform.ADMOB);
        OxAdSdkManager.getInstance().initialize(this) {
            // OxSDK is initialized.
        }
        // 设置⼴告 Sdk 回调。
        OxAdSdkManager.getInstance().adEventCallback = object : AdEventCallback {
            override fun onTrackEvent(name: String, params: Bundle?) {
                super.onTrackEvent(name, params)
                // Sdk 内部进⾏事件上报时，将事件信息暴露给客户端，客户端可根据需求进⾏利⽤
            }
        }
        // 开启Debug模式，注意：⽣产环境需要关闭
        OxAdSdkManager.getInstance().enableDebug(BuildConfig.IS_DEV)
    }

    private fun addFcmListener() {
        CloudMessaging.addListener(object : FcmListener {
            override fun onNotificationReceived(
                notification: RemoteMessage.Notification,
                rawMessage: RemoteMessage
            ) {
                super.onNotificationReceived(notification, rawMessage)
                NotificationUtils.showFcmNotification(this@AiChatApplication, notification)
            }
        })
    }

    private fun schedulePromptLocalNotificationAlarm() {
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, PromptLocalNotificationAlarmReceiver::class.java)
        val alarmIntent =
            PendingIntent.getBroadcast(this, 0, intent, IntentUtil.pendingIntentFlagCompat())

        // 当天晚上 10:15
        val calendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, 22)
            set(Calendar.MINUTE, 15)
            set(Calendar.SECOND, 0)
        }

        // 设置每天触发的定时任务
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            AlarmManager.INTERVAL_DAY, // 间隔一天
            alarmIntent
        )
    }

    private fun initAdjustSDK() {
        val appToken = "hcqjgvosuz9c"
        val environment: String =
            if (BuildConfig.IS_DEV) AdjustConfig.ENVIRONMENT_SANDBOX else AdjustConfig.ENVIRONMENT_PRODUCTION
        val config = AdjustConfig(this, appToken, environment)
        config.setOnAttributionChangedListener { }
        Adjust.onCreate(config)
    }

    class AppLifecycleCallbacks : ActivityLifecycleCallbacks {
        override fun onActivityCreated(p0: Activity, p1: Bundle?) {
        }

        override fun onActivityStarted(p0: Activity) {
        }

        override fun onActivityResumed(p0: Activity) {
            Adjust.onResume()
        }

        override fun onActivityPaused(p0: Activity) {
            Adjust.onPause()
        }

        override fun onActivityStopped(p0: Activity) {
        }

        override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
        }

        override fun onActivityDestroyed(p0: Activity) {
        }

    }
}